import React, { Component } from 'react'
import { Modal, Form, Input, Popover, Tree, InputNumber, Button } from 'antd'

export default class addOrEdit extends Component {
  state = {
    visible: false,
    defaultSelectedKeys: []
  }
  formRef = React.createRef()
  componentDidMount() {
    if(this.props.isAdd) return
    const { id, sort, name, parentName } = this.props.item
    this.formRef.current.setFieldsValue({sort, name, parentName: parentName || '一级部门'})
    this.setState({
      defaultSelectedKeys: [id]
    })
  }
  handleCancel = () => {
    console.log('取消');
    this.formRef.current.resetFields()
    this.props.closeModal()
  }
  handleOk = async () => {
    console.log('确定', this.formRef.current.getFieldsValue());
    await this.formRef.current.validateFields()
    this.formRef.current.resetFields()
    this.props.closeModal()
  }
  handleSelect = (selectedKeys, info) => {
    console.log('selectedKeys', selectedKeys, info);
    this.formRef.current.setFieldsValue({
      parentName: info.node.name
    })
    this.hangdleVisibleChange(false)
  }
  popoverContent = () => {
    return (
      <Tree
        treeData={this.props.treeData}
        selectable
        onSelect={this.handleSelect}
        defaultSelectedKeys={this.state.defaultSelectedKeys}
        fieldNames={{
          title: 'name',
          key: 'id',
          children: 'children'
        }}
      ></Tree>
    )
  }
  hangdleVisibleChange = (visible) => {
    this.setState({
      visible: visible
    })
  }
  render() {
    const { isAdd, visible } = this.props
    return (
      <div>
        <Modal
          title={isAdd ? '新增' : '编辑'}
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form ref={this.formRef} labelAlign="right" labelCol={{span: 5}} initialValues={{sort: 0}}>
            <Form.Item label="名称" name="name" rules={[{required: true}]}>
              <Input placeholder="请输入名称"></Input>
            </Form.Item>
            <Form.Item label="上级部门" name="parentName" rules={[{required: true}]}>
              <Popover
                content={this.popoverContent()}
                visible={this.state.visible}
                trigger="click"
                onVisibleChange={this.hangdleVisibleChange}
              >
                <Form.Item name="parentName" style={{marginBottom: 0}}>
                  <Input readOnly allowClear ></Input>
                </Form.Item>
              </Popover>
            </Form.Item>
            <Form.Item label="排序" name="sort">
              <InputNumber min={0} placeholder="请输入排序"></InputNumber>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
